package com.ding.common;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Pool {

    private Map<String, Channel> socketHolderMap = new HashMap<>();

    public void add(Channel socketHolder) {
        Channel holder = socketHolderMap.put(socketHolder.getId(), socketHolder);
        socketHolder.setPool(this);
        if (holder != null) {
            holder.close();
        }
    }

    public void remove(Channel socketHolder) {
        socketHolderMap.remove(socketHolder.getId());
    }

    public Channel getById(String id) {
        return socketHolderMap.get(id);
    }

    public void closeAll() {
        for (Channel channel : socketHolderMap.values()) {
            channel.close();
        }
    }

    public void closeAndRemoveByIntroducerId(String introducerId) {
        List<String> ids = new ArrayList<>();
        for (Channel channel : socketHolderMap.values()) {
            if (channel.getIntroducerId().equals(introducerId)) {
                channel.close();
                ids.add(channel.getId());
            }
        }
        for (String id : ids) {
            socketHolderMap.remove(id);
        }
    }

    public int size() {
        return socketHolderMap.size();
    }

}
